package mianshi;

/**
 * 腾讯云智一面
 * 给一组数组，给一个目标数s，要是数组子串相加大于等于s，则为合格子串，找出最短子串
 */
public class MinLength {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 4, 5};
        int s = 7;
        System.out.println(minLength2(arr, s));
    }
    public static int minLength(int[] nums,int s) {
        int len = nums.length;
        int minLen = Integer.MAX_VALUE;
        for (int i = 0; i < len; i++) {
            int pre = 0;
            int preLen = 0;
            for (int j = i; j >= 0; j--) {
                pre += nums[j];
                preLen++;
                if (pre >= s) {
                    minLen = Math.min(minLen, preLen);
                    break;
                }
            }
        }
        return minLen;
    }
    public static int minLength2(int[] nums,int s) {
       int  len = nums.length;
       int minLen = Integer.MAX_VALUE;
       int left=0;
        int pre = 0;
        for (int right = 0; right < len; right++) {
            pre += nums[right];
            while(pre>=s){
                minLen = Math.min(minLen, right - left + 1);
                pre -= nums[left];
                left++;
            }
        }
        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }
}
